layui.define(['layer', 'table', 'customform', 'tree', 'form', 'validation', 'treeSelect', 'element', 'selectPlus', 'laydate'], function (exports) {
    "use strict";
    const $ = layui.jquery,
        form = layui.form,
        tree = layui.tree,
        customform = layui.customform,
        table = layui.table;

    let customtree = {
        selecttree: function ({localtable,where},{elem,url,title}) {
            apiRequest({url:url,params: {username: appConfig.userName}}).then(function(e){
                if(e.code == 200){
                    let data = customform.formatdata(e.data,title);
                    tree.render({
                        elem: "#"+elem+"-tree", //指定元素
                        data: data,
                        click: function(node) { //点击节点回调
                            var othis = $($(this)[0].elem).parents(".layui-form-select");
                            othis.removeClass("layui-form-selected").find(".layui-select-title span").
                            html(node.data.title).end().find("input:hidden[name='"+elem+"']").val(node.data.uuid);
                            localtable.where[where] = node.data.uuid;
                            localtable.reload();
                        }
                    });
                    $("."+elem).on("click", ".layui-select-title", function(e) {
                        $(".layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
                        $(this).parents("."+elem).toggleClass("layui-form-selected");
                        layui.stope(e);
                    }).on("click", "dl i", function(e) {
                        layui.stope(e);
                    });
                } else {
                    layer.msg(e.description, {icon: 2, offset: '10px'})
                }
            })
        },
        init: function (data) {
            return customtree.renderBtnElement(data.btn)
        },
        renderBtnElement: function (btns) {
            let btnhtml = ""
            for (let i in btns) {
                let title = "";
                let temp = ""
                for (let key in btns[i]) {
                    "title" == key?title=btns[i][key]:"";
                    "class"==key?(temp += key+"=\"layui-btn layui-btn-xs layui-btn-"+btns[i][key]+"\" "):
                        ("name" == key?(temp += key+"=\""+btns[i][key]+"\" "):
                            ("filter,disabled,event".indexOf(key) != -1?(temp += "lay-"+key+"=\""+btns[i][key]+"\" "):
                                (temp += "data-"+key+"=\""+btns[i][key]+"\" ")));

                }
                btnhtml += `<a ${temp}>${title}</a>`;
            }
            return btnhtml
        },
        render: function (options) { //树表格
            if(options.btn){
                for(let i in options.btn){
                    $("."+options.btn[i]).on("click",function(){
                        let obj = {};
                        obj.event = $(this).attr("lay-event");//按钮类型
                        obj.title = $(this).attr("data-title");//标题
                        obj.url = $(this).attr("data-url");//请求路径
                        obj.give = $(this).attr("data-give");//是否给表单赋值
                        obj.lables = $(this).attr("data-lables");//适用表单
                        obj.data = {};//数据给空
                        options.btnclick?options.formparam.row=options.btnclick(obj):obj;
                        //判断是否直接执行回调
                        if($(this).attr("data-callback")){
                            return options.callback(options);
                        }
                        $(this).attr("data-type")=="msg"?customtree.openmsg(options):customtree.openwind(options);
                    });
                }
            }
            table.on('tool('+options.filter+')', function (obj) {
                obj.title = $(this).attr("data-title");//标题
                obj.url = $(this).attr("data-url");//请求路径
                obj.give = $(this).attr("data-give");//是否给表单赋值
                options.click?options.formparam.row=options.click(obj):obj;
                //判断是否直接执行回调
                if($(this).attr("data-callback")){
                    return options.callback(options);
                }

                $(this).attr("data-type")=="msg"?customtree.openmsg(options):customtree.openwind(options);
            });
        },
        openmsg: function (options){
            layer.msg(`确定${options.formparam.row.title}此项？`, {
                time: 20000,
                btn: ['确定', '取消'],
                yes: function (index) {
                    options.confirm?options.confirm(options):null;
                    apiRequestCru({
                        url: options.formparam.row.url,
                        params: options.formparam.row.data
                    }).then(res => {
                        if (res.code == 200) {
                            layer.msg(`${options.formparam.row.title}成功！`, {icon: 1, offset: '10px'});
                            options.success?options.success(options):null;
                        } else {
                            layer.msg(res.description, {icon: 2, offset: '10px'})
                        }
                        layer.close(index)
                    }).catch(function (msg) {
                        layer.msg(msg, {icon: 2, offset: '10px'})
                    })

                }
            })
        },
        openwind: function (options) {
            layer.open({
                type: 1,
                title: false,
                closeBtn: false,
                area: '600px',
                shade: 0,
                id: options.formparam.filter + '-lay', //设定一个id，防止重复弹出
                btn: ['确认', '取消'],
                btnAlign: 'c',
                moveType: 0, //拖拽模式，0或者1
                content: customform.render(options.formparam, options.formparam.row.lables&&options.formparam.row.lables!="default"?options.formparam[options.formparam.row.lables]:options.formparam.lables),
                success: function () {
                    //表单渲染
                    form.render();
                    //父值赋值到表单
                    //{parentname:"classid",childname:"classid",placeholder:"请选择字典类目",required:true,type:"all",show:true}

                    for(let i in options.formparam.injection){
                        if(options.formparam.injection[i].show){
                            let type = options.formparam.injection[i].type;
                            let flag = type=="all"||(type.indexOf(options.formparam.row.event)!==-1)?true:false;
                            if(flag){
                                if(options.formparam.injection[i].required){
                                    let val = options.formparam.row.data[options.formparam.injection[i].parentname];
                                    if(val=='' || val==undefined || val=='undefined'){
                                        if(options.formparam.injection[i].placeholder){
                                            return layer.msg(options.formparam.injection[i].placeholder, {icon: 2, offset: '10px'});
                                        }
                                        return layer.msg(`页面注入值为空，后续操作可能会造成数据异常，联系技术员解决!`, {icon: 2, offset: '10px'});
                                    }
                                }
                                let data = {};
                                data[options.formparam.injection[i].childname] = options.formparam.row.data[options.formparam.injection[i].parentname];
                                form.val(options.formparam.filter + '-example', data);
                            }
                        }
                    }
                    if (options.formparam.row.give) {
                        //处理开关按钮
                        if(options.formparam.switch && options.formparam.switch.length > 0){
                            for(let i in options.formparam.switch){
                                let val = options.formparam.row.data[options.formparam.switch[i].field];
                                if(val == options.formparam.switch[i].ison){
                                    options.formparam.row.data[options.formparam.switch[i].field] = "on";
                                } else {
                                    delete options.formparam.row.data[options.formparam.switch[i].field];
                                }
                            }
                        }
                        form.val(options.formparam.filter + '-example', options.formparam.row.data);
                    }

                    options.load?options.done(options):null;
                },
                yes: function (index) {
                    //获取表单
                    let formdata = form.val(options.formparam.filter + '-example');
                    //处理开关按钮
                    if(options.formparam.switch && options.formparam.switch.length > 0){
                        for(let i in options.formparam.switch){
                            if(formdata[options.formparam.switch[i].field] == options.formparam.switch[i].ison){
                                formdata[options.formparam.switch[i].field] = options.formparam.switch[i].ison;
                            } else {
                                formdata[options.formparam.switch[i].field] = options.formparam.switch[i].isoff;
                            }
                        }
                    }
                    //注入值
                    for(let i in options.formparam.injection){
                        if(!options.formparam.injection[i].show){
                            let type = options.formparam.injection[i].type;
                            let flag = type=="all"||(type.indexOf(options.formparam.row.event)!==-1)?true:false;
                            if(flag){
                                if(options.formparam.injection[i].required){
                                    let val = options.formparam.row.data[options.formparam.injection[i].parentname];
                                    if(val=='' || val==undefined || val=='undefined'){
                                        if(options.formparam.injection[i].placeholder){
                                            return layer.msg(options.formparam.injection[i].placeholder, {icon: 2, offset: '10px'});
                                        }
                                        return layer.msg(`页面注入值为空，后续操作可能会造成数据异常，联系技术员解决!`, {icon: 2, offset: '10px'});
                                    }
                                }
                                formdata[options.formparam.injection[i].childname] = options.formparam.row.data[options.formparam.injection[i].parentname];
                            }
                        }
                    }
                    let record = options.confirm?options.confirm(options,formdata):"";
                    options.confirm?formdata=(record?record:formdata):null;
                    //数据校验
                    if (!customform.virifyForm(formdata)) return;
                    options.formparam.row.formdata = formdata;
                    apiRequestCru({
                        url: options.formparam.row.url,
                        params: formdata
                    }).then(function (e) {
                        if (e.code == 200) {
                            //不管有无返回数据，给上就行
                            options.formparam.row.result = e.data;
                            layer.msg(`${options.formparam.row.title}成功!`, {icon: 1, offset: '10px'});
                            options.success?options.success(options):null;
                        } else {
                            layer.msg(e.description, {icon: 2, offset: '10px'})
                        }
                        layer.close(index)
                    }).catch(function (msg) {
                        layer.msg(msg, {icon: 2, offset: '10px'})
                    })
                }
            })
        }
    }
    exports('customtree', customtree)
});